package by.pavlyukevich.paymentsystem.panel;

import java.util.GregorianCalendar;

import javax.inject.Inject;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;

import by.pavlyukevich.paymentsystem.add.UpdateEvent;
import by.pavlyukevich.paymentsystem.add.ErrorEvent;
import by.pavlyukevich.paymentsystem.datamodel.Account;
import by.pavlyukevich.paymentsystem.datamodel.Transaction;
import by.pavlyukevich.paymentsystem.services.AccountService;
import by.pavlyukevich.paymentsystem.services.TransactionService;

public class PaymentPanel extends Panel {

	@Inject
	private AccountService accountService;
	@Inject
	private TransactionService transactionService;

	public PaymentPanel(String id, Transaction transaction) {
		super(id);
		Form<Transaction> form = new Form<Transaction>("form",
				new CompoundPropertyModel<Transaction>(transaction));
		add(form);

		form.add(new DropDownChoice<Account>("payeeAccount", new PropertyModel<Account>(
				transaction, "payeeAccount"), accountService.getList(),
				new IChoiceRenderer<Account>() {
					@Override
					public Object getDisplayValue(Account account) {
						return account.getAccountNumber();
					}

					@Override
					public String getIdValue(Account object, int index) {
						return Integer.toString(index);
					}
				}).add(new PropertyValidator<Account>()));

		form.add(new TextField<String>("amount").add(new PropertyValidator<String>()));

		form.add(new AjaxSubmitLink("pay") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				transaction.setDate(GregorianCalendar.getInstance().getTime());

				String result = transactionService.validateAndBlock(transaction);

				if (result != null) {
					error(new ResourceModel(result).getObject());
					send(getPage(), Broadcast.BREADTH, new ErrorEvent(target));
				} else {
					transaction.setSenderAccount(transaction.getSenderCard().getAccount());
					transactionService.saveOrUpdate(transaction);
					transactionService.executeTransaction(transaction);
					send(getPage(), Broadcast.BREADTH, new UpdateEvent(target, transaction
							.getSenderCard().getAccount()));

				}
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				send(getPage(), Broadcast.BREADTH, new ErrorEvent(target));
			}
		});
	}
}
